import { createRouter, createWebHashHistory } from 'vue-router'
import LoginView from '@/views/login/LoginView.vue'
import IndexView from '@/views/index/IndexView.vue'
import store from '@/store'
import NovelListView from '@/views/index/novel/NovelListView.vue'
import AddNovelView from '@/views/index/novel/NoveAddlView.vue'
import NovelDetailView from '@/views/index/novel/NovelDetailView.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { title: '后台登录' }
  },
  {
    path: '/index',
    name: 'index',
    component: IndexView,
    meta: { title: '后台首页' },
    children: [
      {
        path: '/index/novelList',
        name: 'novelList',
        component: NovelListView,
        meta: { title: '小说列表' }
      },
      {
        path: '/index/novelAdd',
        name: 'novelAdd',
        component: AddNovelView,
        meta: { title: '添加小说' }
      },
      {
        path: '/index/novel/:id',
        name: 'novelDetail',
        component: NovelDetailView,
        meta: { title: '小说详情' }
      },
    ]
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 禁止游客访问的路径
const authUrl = []

router.beforeEach((to, from, next) => {
  // 1. to 往哪里去， 到哪去的路由信息对象
  // 2. from 从哪里来， 从哪来的路由信息对象
  // 3. next() 是否放行
  // 如果next()调用，就是放行
  // next(路径) 拦截到某个路径页面
  const token = store.state.user.userInfo.token
  // console.log('token:', token)
  document.title = to.meta.title || '默认标题';
  if (!authUrl.includes(to.path)) {
    next()
    return
  }

  if (token) {
    next()
    // console.log('11111')
  } else {
    // console.log('22222')
    next('/login')
  }
})

export default router
